﻿using Common;
using Common.Enums;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace enterprise.Website.Core.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    [LoginAuthorize]
    public class ContentClassController : ControllerBase
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;
        public ContentClassController(SqlContext sqlContext, ICache cache)
        {
            _sqlContext = sqlContext;
            _cache = cache;
        }

        /// <summary>
        /// 获取网站栏目列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<ContentClassTreeTableModel>>> Get()
        {
            var result = new ApiResult<List<ContentClassTreeTableModel>> { Success = false, Message = "暂无数据", Code = -1 };
            //获取所有语言
            var LanguageTypes = await _sqlContext.QueryListAsync<LanguageType>();
            if (LanguageTypes != null)
            {
                var resultData = new List<ContentClassTreeTableModel>();
                //获取最上层，各语言站
                var TopList = LanguageTypes.Select(m => new ContentClassTreeTableModel
                {
                    Id = $"Language_{m.Id}",
                    ParentId ="0",
                    ClassName=m.Language,
                    isLanguage=true
                }).ToList();
                resultData.AddRange(TopList);

                //获取所有栏目
                var TopContentClass = await _sqlContext.QueryListAsync<ContentClass>(orderBy:"Sort Desc");
                resultData.AddRange(TopContentClass.Select(m=>new ContentClassTreeTableModel
                {
                    Id = m.Id.ToString(),
                    ParentId = m.ParentId == 0 ? $"Language_{m.LanguageId}": m.ParentId.ToString(),
                    ClassName = m.ClassName,
                    isLanguage = false
                }).ToList());

                if (resultData.Count > 0)
                {
                    result.Data = resultData;
                    result.Success = true;
                    result.Code = 0;
                    result.Message = "获取成功";
                }
            }
            return result;
        }

        /// <summary>
        /// 获取栏目板块
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<ContentClass>> Get(int id = 0)
        {
            var result = new ApiResult<ContentClass> { Success = false, Message = "暂无数据", Code = -1 };
            if (id > 0)
            {
                var contentClassInfo = await _sqlContext.QueryInfoAsync<ContentClass>(m => m.Id == id);
                if (contentClassInfo!=null)
                {
                    result.Success = true;
                    result.Message = "获取成功";
                    result.Data = contentClassInfo;
                }
            }
            return result;
        }

        /// <summary>
        /// 获取栏目详情中，上级选择级联下拉框
        /// </summary>
        /// <param name="ContentId">当前栏目Id</param>
        /// <returns></returns>
        [HttpGet("GetContentTreeList")]
        public async Task<object> GetContentTreeList(int ContentId = 0)
        {
            var result = new ApiResult<List<treeSelectModel>> { Success = false, Message = "暂无数据", Code = -1 };
            ContentClass contentClass = null;
            if (ContentId != 0)
            {
                contentClass = await _sqlContext.QueryInfoAsync<ContentClass>(m => m.Id == ContentId, orderBy: "Sort desc");
            }
            //获取所有语言
            var LanguageTypes = await _sqlContext.QueryListAsync<LanguageType>();
            if (LanguageTypes != null)
            {
                var resultData=LanguageTypes.Select(m=>new treeSelectModel 
                {
                    id= $"Language_{m.Id}",
                    name=m.Language,
                    open= contentClass!=null ? contentClass.LanguageId==m.Id:false,
                    @checked= contentClass != null ? contentClass.LanguageId == m.Id : false,
                    children = QueryLanguageNext(m.Id, contentClass != null ? contentClass.LanguageId == m.Id : false, ContentId),
                    LanguageId=m.Id,
                    isLanguage=true
                }).ToList();
                if (resultData != null&&resultData.Count>0)
                {
                    result.Data = resultData;
                    return resultData;
                }
            }
            return result;
        }

        /// <summary>
        /// 新增栏目
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> Post([FromBody] ContentClass data)
        {
            var result = new ApiResult<int> { Success = false, Message = "保存失败" };
            if (data != null)
            {
                //判断是否有相同的
                var hasTo = await _sqlContext.QueryCountAsync<ContentClass>(m => m.ClassName == data.ClassName && m.ParentId == data.ParentId);
                if (hasTo > 0)
                {
                    result.Message = "该栏目下有相同子栏目，请修改名称";
                    return result;
                }
                if (!data.ClassType.HasValue)
                {
                    result.Message = "请选择栏目类型";
                    return result;
                }
                if (data.ClassType==(int)ClassType.Content)
                {
                    if (data.Path.IsNullOrWhiteSpace())
                    {
                        result.Message = "内容页必须填写访问路径";
                        return result;
                    }
                    if (data.Path.IsChinese())
                    {
                        result.Message = "访问路径不得含有中文";
                        return result;
                    }
                    if (data.Path.Length < 3)
                    {
                        result.Message = "访问路径必须大于3个字符";
                        return result;
                    }
                }
                var id=await _sqlContext.AddAsync(data);
                if (id > 0)
                {
                    result.Data = id.ObjToInt();
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.ContentClassKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 修改栏目
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        [HttpPut("{id}")]
        public async Task<ApiResult> Put(int id, [FromBody] ContentClass data)
        {
            var result = new ApiResult<ContentClass> { Success = false, Message = "保存失败" };
            if (data != null)
            {
                data.Id = id;
                if (!data.ClassType.HasValue)
                {
                    result.Message = "请选择栏目类型";
                    return result;
                }
                if (data.ClassType == (int)ClassType.Content)
                {
                    if (data.Path.IsNullOrWhiteSpace())
                    {
                        result.Message = "内容页必须填写访问路径";
                        return result;
                    }
                    if (data.Path.IsChinese())
                    {
                        result.Message = "访问路径不得含有中文";
                        return result;
                    }
                    if (data.Path.Length < 3)
                    {
                        result.Message = "访问路径必须大于3个字符";
                        return result;
                    }
                }
                var Count = await _sqlContext.UpdateAsync(data);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove($"{SystemConstConfig.ContentClassKey}_{data.LanguageId}");
                }
            }
            return result;
        }

        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id = 0)
        {
            var result = new ApiResult<ContentClass> { Success = false, Message = "删除失败" };
            if (id > 0)
            {
                var hasNext = await _sqlContext.QueryCountAsync<ContentClass>(m => m.ParentId == id);
                if (hasNext > 0)//如果该栏目包括子集，则无法删除
                {
                    result.Message = "该栏目包括子集，无法删除";
                    return result;
                }
                var contentClassInfo = await _sqlContext.QueryInfoAsync<ContentClass>(m => m.Id == id);
                if (contentClassInfo != null)
                {
                    var Count = await _sqlContext.DeleteAsync<ContentClass>(m => m.Id == id);
                    if (Count > 0)
                    {
                        result.Success = true;
                        result.Message = "删除成功";
                        _cache.Remove($"{SystemConstConfig.ContentClassKey}_{contentClassInfo.LanguageId}");

                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 查询栏目下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("QueryContentSelect")]
        public async Task<object> QueryContentSelect(int? classType=null)
        {
            Expression<Func<ContentClass, bool>> whereException = m => true;
            if (classType.HasValue)
            {
                whereException = whereException.And(m => m.ClassType == classType.Value);
            }
            var list = await _sqlContext.QueryListAsync<ContentClass>(whereException);
            if (list != null && list.Count > 0)
            {
                return list.Select(m => new { text = m.ClassName, value = m.Id }).ToList();
            }
            else
            {
                return new List<object>();
            }
        }


        /// <summary>
        /// 获取各个语言下的顶级栏目
        /// </summary>
        /// <param name="LanguageId"></param>
        /// <param name="isChecked"></param>
        /// <returns></returns>
        private List<treeSelectModel> QueryLanguageNext(int LanguageId, bool isChecked,int noHasId)
        {
            List<treeSelectModel> result = null;
            var contentClass = _sqlContext.QueryList<ContentClass>(m => m.LanguageId == LanguageId && m.ParentId==0 && m.Id != noHasId,orderBy:"Sort desc");
            if (contentClass != null && contentClass.Count > 0)
            {
                result = contentClass.Select(m => new treeSelectModel
                {
                    id = m.Id.ToString(),
                    name = m.ClassName +$"({((ClassType)m.ClassType).GetDescription()})",
                    children = QueryContentNext(m.Id, isChecked, noHasId),
                    open = isChecked,
                    @checked = isChecked,
                    LanguageId = m.LanguageId,
                    isLanguage = false
                }).ToList();
            }
            return result;
        }

        /// <summary>
        /// 递归获取子栏目
        /// </summary>
        /// <param name="CId"></param>
        /// <returns></returns>
        private List<treeSelectModel> QueryContentNext(int CId, bool isChecked,int noHasId)
        {
            List<treeSelectModel> result = null;
            var contentClass = _sqlContext.QueryList<ContentClass>(m => m.ParentId == CId && m.Id != noHasId, orderBy: "Sort desc");
            if (contentClass != null && contentClass.Count > 0)
            {
                result = contentClass.Select(m => new treeSelectModel
                {
                    id = m.Id.ToString(),
                    name = m.ClassName + $"({((ClassType)m.ClassType).GetDescription()})",
                    children = QueryContentNext(m.Id, isChecked, noHasId),
                    open = isChecked,
                    @checked = isChecked,
                    LanguageId = m.LanguageId,
                    isLanguage = false
                }).ToList();
            }
            return result;
        }


    }
}
